<script setup>
import { ref } from 'vue';

import { User, Lock, Message, Key, Stopwatch } from '@element-plus/icons-vue';
import {
  appUserRegisterVerifyCodeMailService,
  appUserRegisterService
} from '@/apis/appuser';

const regFormDefault = {
  email: '',
  userName: '',
  password: '',
  rePassword: ''
};

const regFormModel = ref({
  ...regFormDefault
});

const regForm = ref();

// 注册验证码相关
const regVerifyCodeBtn = ref({
  disabled: false,
  text: '获取验证码',
  loading: false
});
const onRegVerifyCodeBtnClick = async () => {
  await regForm.value.validateField('email');

  // （网络请求）loading 开启
  regVerifyCodeBtn.value.loading = true;
  let reqData = {
    email: regFormModel.value.email
  };
  await appUserRegisterVerifyCodeMailService(reqData)
    .then((res) => {
      ElMessage.success('请求验证码成功');
      // （网络请求）loading 关闭
      regVerifyCodeBtn.value.loading = false;

      // （防止重复点击）禁用开启
      regVerifyCodeBtn.value.disabled = true;

      let remainingSeconds = res.data;
      regVerifyCodeBtn.value.text = `（${remainingSeconds}）`;
      var handler = setInterval(() => {
        if (remainingSeconds >= 1) {
          regVerifyCodeBtn.value.text = `（${--remainingSeconds}）`;
          return;
        }

        // （防止重复点击）禁用关闭
        regVerifyCodeBtn.value.disabled = false;
        regVerifyCodeBtn.value.text = '再次获取';
        clearInterval(handler);
      }, 1000);
    })
    // 异常情况
    .catch(() => {
      // （网络请求）loading 关闭
      regVerifyCodeBtn.value.loading = false;
    });
};

const doRegister = async () => {
  await regForm.value.validate();

  let res = await appUserRegisterService(regFormModel.value);
  ElMessage.success(res.msg);
  finishRegister();
};

const emits = defineEmits(['finishRegister']);
const finishRegister = () => {
  emits('finishRegister');
};

const rules = {
  email: [
    {
      type: 'email',
      required: true,
      message: '请输入正确的电子邮箱',
      trigger: 'blur'
    }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是 5-10 位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15 位的非空字符',
      trigger: 'blur'
    }
  ],
  rePassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15 位的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== regFormModel.value.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback(); // 校验成功后也需要 callback
        }
      },
      trigger: 'blur'
    }
  ]
};

const resetRegister = () => {
  regFormModel.value = ref({
    ...regFormDefault
  });
};

defineExpose({
  resetRegister
});
</script>

<template>
  <!-- 注册相关表单 -->
  <el-form
    :model="regFormModel"
    :rules="rules"
    ref="regForm"
    size="large"
    autocomplete="off"
  >
    <el-form-item>
      <h1>注册</h1>
    </el-form-item>
    <el-form-item prop="email">
      <el-input
        v-model="regFormModel.email"
        :prefix-icon="Message"
        placeholder="请输入邮箱地址"
      ></el-input>
    </el-form-item>
    <el-form-item prop="verifyCode" class="verify-code-container">
      <el-input
        v-model="regFormModel.verifyCode"
        :prefix-icon="Key"
        placeholder="请输入收到的验证码"
      ></el-input>
      <el-button
        class="verify-code-btn"
        type="primary"
        :disabled="regVerifyCodeBtn.disabled"
        :loading="regVerifyCodeBtn.loading"
        :loading-icon="Stopwatch"
        @click="onRegVerifyCodeBtnClick"
      >
        {{ regVerifyCodeBtn.text }}
      </el-button>
    </el-form-item>
    <el-form-item prop="userName">
      <el-input
        v-model="regFormModel.userName"
        :prefix-icon="User"
        placeholder="请输入用户名"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="regFormModel.password"
        :prefix-icon="Lock"
        type="password"
        show-password
        placeholder="请输入密码"
      ></el-input>
    </el-form-item>
    <el-form-item prop="rePassword">
      <el-input
        v-model="regFormModel.rePassword"
        :prefix-icon="Lock"
        type="password"
        show-password
        placeholder="请再次输入密码"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button
        @click="doRegister"
        class="button"
        type="primary"
        auto-insert-space
      >
        注册
      </el-button>
    </el-form-item>
    <el-form-item class="flex">
      <el-link type="info" :underline="false" @click="finishRegister()">
        ← 返回
      </el-link>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
.button {
  width: 100%;
}

.verify-code-container :deep(.el-form-item__content) {
  flex-wrap: nowrap;
  justify-content: space-between;
}

.verify-code-btn {
  flex-basis: 150px;
}
</style>
